package transport.connection;

import io.netty.channel.Channel;
import org.apache.log4j.Logger;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 通道连接池
 *
 * */
public class ConnectionPool {

    private static Logger logger = Logger.getLogger(ConnectionPool.class);

    private ConnectionPool() {
    }

    private static Map<String, Channel> channelMap = new ConcurrentHashMap<String, Channel>(1024);

    /**
     * 添加链接
     *
     * */
    public static boolean add(String uniqueKey, Channel channel) {
        Channel result = channelMap.put(uniqueKey, channel);
        if (null == result) {
            logger.info("链接池 添加成功(uniqueKey=" + uniqueKey + " channel=" + result + ")");
            return true;
        } else {
            logger.info("链接池 添加失败(uniqueKey=" + uniqueKey + " channel=" + result + ")");
            return false;
        }
    }

    /**
     * 移除链接
     *
     * */
    public static boolean remove(String uniqueKey) {
        Channel result = channelMap.remove(uniqueKey);
        if (null == result) {
            logger.info("链接池 移除成功(uniqueKey=" + uniqueKey + " channel=" + result + ")");
            return true;
        } else {
            logger.info("链接池 移除失败(uniqueKey=" + uniqueKey + " channel=" + result + ")");
            return false;
        }
    }

    /**
     * 查找链接通道
     *
     * */
    public static Channel query(String uniqueKey) {
        return channelMap.get(uniqueKey);
    }
}
